﻿using System;
using System.Configuration;
using System.Linq;
using System.Linq.Dynamic;
using System.Web;
using System.Web.Mvc;
using VCC.CMS.Components;
using VCC.CMS.Properties;
using VCC.CMS.ViewModels;
using VCC.Lib.Common;
using VCC.Lib.Helpers;
using VCC.Lib.Mail;
using VCC.Lib.Paging;
using VCC.Model;
using MyUtility;
using System.Web.UI.MobileControls;
using System.IO;

namespace VCC.CMS.Controllers
{
	[RoleHelper(Roles = RoleSystem.Article)]
    public class ArticleController : BaseController
    {
        /// <summary>
        /// Created by: Vietlv
        /// Created date: 01/04/2014
        /// Description: Manage Articles - Class Article controler;
        /// </summary>

        ChoVietDataContext eDataContext = new ChoVietDataContext();
        
        #region GET: /Article/ Index(int? Page)
        public ActionResult Index(int? page)
        {
            try
            {
                    if (page == null) page = 1;
                    string order = UserState.getUserStateFromRequest("article.order", "order", "ID").ToString();
                    string orderDir = UserState.getUserStateFromRequest("article.orderDir", "orderDir", "desc").ToString();
                    int catID = Convert.ToInt32(UserState.getUserStateFromRequest("article.CatID", "CatID", 0));
                    int currentHot = Convert.ToInt32(UserState.getUserStateFromRequest("article.HotStatus", "HotStatus", 0));
                    int currentPub = Convert.ToInt32(UserState.getUserStateFromRequest("article.PubStatus", "PubStatus", 0));
                    string keyword = UserState.getUserStateFromRequest("article.Keyword", "Keyword", "").ToString();
                    keyword = keyword.Trim();
                    int pageSize = int.Parse(UserState.getUserStateFromRequest("article.pageSize", "PageSize", 20).ToString());
                    ArticleIndexViewModel model = new ArticleIndexViewModel();
                    var articles = eDataContext.Articles
                        .Where (a => catID > 0 ? a.CatID == catID : true )
                        .Where(a => currentHot > 0 ? a.HotYN == (currentHot == 1 ? true : false) : true)
                        .Where(a => currentPub > 0 ? a.PubYN == (currentPub == 1 ? true : false) : true)
                        .Where(a => (string.IsNullOrEmpty(keyword) ? true :
                            (a.Title.ToLower().Contains(keyword.ToLower()) ||
                            a.Summary.ToLower().Contains(keyword.ToLower()) ||
                            a.ArticleContent.Contains(keyword)
                            )))
                        .OrderBy(string.Format("{0} {1}", order, orderDir))
                        .ToPagedList(page.Value - 1, pageSize);

                    var articleCategory = ArticleManager.GetListCategory();
                    var hosts = Utils.StringToDictionary(Settings.Default.ArticleHotStatus.ToString(), ",");
                    var pubs = Utils.StringToDictionary(Settings.Default.ArticlePubStatus.ToString(), ",");

                    ViewData["orderDir"] = orderDir;
                    ViewData["order"] = order;

                    return View(new ArticleIndexViewModel
                    {
                        Articles = articles,
                        Categories = articleCategory,
                        HotStatus = hosts,
                        PubStatus = pubs,
                        CurrentCat = catID,
                        CurrentHotStatus = currentHot,
                        CurrentPubStatus = currentPub,
                        Keyword = keyword,
                        ImageRootUrl =Settings.Default.SiteRootUrl
                    });
            }
            catch (Exception exp)
            {
                ViewData["MessageInfo"] = exp.Message;
                return View();
            }
        }
        #endregion
        
        
        #region GET: /Article/Details(int id)
        public ActionResult Details(int id)
        {
            ArticleEditViewModel model = new ArticleEditViewModel();
            model.Article = eDataContext.Articles.Where(a => a.ID == id).SingleOrDefault();
            model.ImageRootUrl = Settings.Default.SiteRootUrl;
            return View(model);
        }
        #endregion

        #region GET: /Article/Create

        public ActionResult Create()
        {
            ArticleEditViewModel model = new ArticleEditViewModel();
            model.Language = eDataContext.Languages.Where(e => e.ActiveYN == true).ToList();
            model.ArticleCategories = eDataContext.ArticleCategories.Where(e => e.ActiveYN == true).ToList();
            return View(model);
        }
        #endregion
        
        #region POST: /Article/Create
        [ValidateInput(false)]
        [HttpPost]
        public ActionResult Create(ArticleEditViewModel a)
        {
            try
            {
                if (eDataContext.Connection.State == System.Data.ConnectionState.Closed) eDataContext.Connection.Open();
                eDataContext.Transaction = eDataContext.Connection.BeginTransaction();                                  
                // TODO: Add insert logic here
                UpdateModel(a);
                a.Article.PubYN = true;
                a.Article.HotYN = true;
                a.Article.Summary = a.Article.Title;
                a.Article.AddDate = DateTime.Now;
                a.Article.AddBy = UserManager.GetUserId();
                eDataContext.Articles.InsertOnSubmit(a.Article);
                eDataContext.SubmitChanges();
                eDataContext.Transaction.Commit();
                return RedirectToAction("Index");
            }
            catch(Exception exp)
            {
                eDataContext.Transaction.Rollback();
                Messages.AddFlashException(exp);
                return View();
            }
        }
        #endregion
        
        #region GET: /Article/Edit/5
        public ActionResult Edit(int id)
        {
            ArticleEditViewModel model = new ArticleEditViewModel();
            model.Article = eDataContext.Articles.Where(a => a.ID == id).SingleOrDefault();
            model.ArticleCategories = ArticleManager.GetListCategory();
            model.Language = eDataContext.Languages.ToList();
            //model.ArticleTypes = eDataContext.ArticleTypes.ToList();
            model.ImageRootUrl = Settings.Default.SiteRootUrl;
            return View(model);
        }
        #endregion
        
        #region POST: /Article/Edit/5
        [ValidateInput(false)]
        [HttpPost]
        public ActionResult Edit(int id, ArticleEditViewModel a)
        {
            try
            {
                if (eDataContext.Connection.State == System.Data.ConnectionState.Closed) eDataContext.Connection.Open();
                eDataContext.Transaction = eDataContext.Connection.BeginTransaction();
                // TODO: Add update logic here
                a.Article = eDataContext.Articles.Where(ar => ar.ID == id).SingleOrDefault();
                a.Article.CatID = Request["CatID"] != string.Empty ? Utils.ParseInt(Request["CatID"]) : (int?)null;
                //a.Article.TypeID = Request["TypeID"] != string.Empty ? Utils.ParseInt(Request["TypeID"]) : (int?)null;
                a.Article.PubYN = Request["PublishYN"] != "false" ? true : false;
                a.Article.HotYN = Request["HotYN"] != "false" ? true : false;
                UpdateModel(a);
               
                //image upload
                HttpPostedFileBase fileImage = Request.Files["ArticleImage"];
                if (fileImage != null && fileImage.FileName.Length > 0)
                {
                    //Delete old image
                    if (!string.IsNullOrEmpty(a.Article.ImagePath) && System.IO.File.Exists(string.Format("{0}{1}", Settings.Default.SiteRootPath, a.Article.ImagePath.Replace('/','\\'))))
                        Uploads.DeleteFile(string.Format("{0}{1}", Settings.Default.SiteRootPath, a.Article.ImagePath.Replace('/','\\')));

                    //DO upload new image
                    a.Article.ImagePath = Uploads.UploadFile(fileImage, Settings.Default.ArticleAvataPath, Settings.Default.SiteRootPath, a.Article.ID.ToString());
                }                
                eDataContext.SubmitChanges();
                eDataContext.Transaction.Commit();
                return RedirectToAction("Index");
            }
            catch(Exception exp)
            {
                eDataContext.Transaction.Rollback();
                Messages.AddFlashException(exp);
                return View(a);
            }
        }
        #endregion       
        
        #region GET: /Article/Delete/5
        public ActionResult Delete(int id)
        {
            try
            {
                    var item = eDataContext.Articles.Single(e => e.ID == id);
                    return View(item);
            }
            catch (Exception exp)
            {
                Messages.AddFlashException(exp);
                return View();
            }
        }
        #endregion

        #region POST: /Article/Delete/5
        [HttpPost]
        public ActionResult Delete(int id, FormCollection collection)
        {
            var item = eDataContext.Articles.Single(e => e.ID == id);
            try
            {       
                    if (item != null)
                    {                        
                        //Delete avatar image
                        if (!string.IsNullOrEmpty(item.ImagePath) && System.IO.File.Exists(string.Format("{0}{1}", Settings.Default.SiteRootPath, item.ImagePath.Replace('/', '\\'))))
                            Uploads.DeleteFile(string.Format("{0}{1}", Settings.Default.SiteRootPath, item.ImagePath.Replace('/', '\\')));
                        // Delete current article
                        eDataContext.Articles.DeleteOnSubmit(item);
                        eDataContext.SubmitChanges();
                    }
                    return RedirectToAction("Index");
            }
            catch (Exception exp)
            {
                Messages.AddFlashException(exp);
                return View(item);
            }
        }
        #endregion
        /*
        #region DeleteFile(int documentID)
        public ActionResult DeleteFile(int id)
        {
            try
            {   
                var currentDocument = eDataContext.Documents.Where(e => e.ID == id).SingleOrDefault();
                // Delete in DocumentInArticles 
                var currentArticleMap = eDataContext.DocumentsInArticles.Where(e => e.DocumentID == id).FirstOrDefault();
                var articleID = currentArticleMap.ArticleID;
                if (currentArticleMap != null)
                    eDataContext.DocumentsInArticles.DeleteOnSubmit(currentArticleMap);
                // Delete File in Hardisk
                var pathFile = Settings.Default.SiteRootPath + Settings.Default.DocumentInArticleRootPath + currentDocument.ID +"_" + currentDocument.Path;
                Uploads.DeleteFile(pathFile);
                // Delete File in table Document
                if (currentDocument != null) eDataContext.Documents.DeleteOnSubmit(currentDocument);
                eDataContext.SubmitChanges();
                return RedirectToAction("Edit/" + articleID);
            }
            catch (Exception exp)
            {
                ViewData[Messages.MessageInfo] = exp.Message;
                throw exp;
            }
            
        }
#endregion

        */
    }
}
